package com.stars.pao.aicloud.controller;


import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.stars.pao.aicloud.entity.Answer;
import com.stars.pao.aicloud.entity.enums.AiModelEnum;
import com.stars.pao.aicloud.entity.enums.AiTypeEnum;
import com.stars.pao.aicloud.service.IAnswerService;
import com.stars.pao.aicloud.util.AppVariable;
import com.stars.pao.aicloud.util.MinIoUtil;
import com.stars.pao.aicloud.util.ResponseEntity;
import com.stars.pao.aicloud.util.SecurityUtil;
import com.stars.pao.aicloud.util.idempotent.Idempotent;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import okhttp3.HttpUrl;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


@Tag(name = "讯飞大模型控制器")
//讯飞大模型调用
@RestController
@RequestMapping("/xunfei")
public class XunfeiController {

    @Value("${xunfei.chat.url}")
    private String chatUrl;
    @Value("${xunfei.chat.api-key}")
    private String chatApiKey;
    @Value("${xunfei.chat.api-secret}")
    private String chatApiSecret;
    @Value("${xunfei.draw.host-url}")
    private String hostUrl;
    @Value("${xunfei.draw.api-key}")
    private String drawApiKey;
    @Value("${xunfei.draw.api-secret}")
    private String drawApiSecret;
    @Value("${xunfei.draw.app-id}")
    private String appId;

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private IAnswerService answerService;

    @Resource
    private MinIoUtil minioUtil;

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 调用对话功能
     */
    @PostMapping("/chat")
    @Idempotent
    public ResponseEntity chat(String question) throws JsonProcessingException {
        if (!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.XUNFEI.getValue(),
                AiTypeEnum.CHAT.getValue());
        String result = ""; // 大模型返回的结构
        String content = "";
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁请求，请稍后再试");
            }
            String bodyJson = "{\n" +
                    "    \"model\":\"generalv3.5\",\n" +
                    "    \"messages\": [\n" +
                    "        {\n" +
                    "            \"role\": \"user\",\n" +
                    "            \"content\": \"" + question + "\"\n" +
                    "        }\n" +
                    "    ]\n" +
                    "}";
            result = HttpRequest.post(chatUrl)
                    .header("Content-Type", "application/json")
                    .header("Authorization", "Bearer " + chatApiKey + ":" + chatApiSecret)
                    .body(bodyJson)
                    .execute()
                    .body();

            HashMap<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);
            if (!resultMap.get("code").toString().equals("0")) {
                return ResponseEntity.fail(resultMap.get("message").toString());
            }
            ArrayList choices = (ArrayList) resultMap.get("choices");
            LinkedHashMap<String, Object> choiceMap = (LinkedHashMap) choices.get(0);
            LinkedHashMap<String, Object> message = (LinkedHashMap<String, Object>) choiceMap.get("message");
            content = message.get("content").toString();

            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(content);
            answer.setUid(uid);
            answer.setType(AiTypeEnum.CHAT.getValue());
            answer.setModel(AiModelEnum.XUNFEI.getValue());
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            rLock.unlock();
        }
        if(!isSave) {
            return ResponseEntity.fail("数据保存失败，请重试");
        }
            return ResponseEntity.succ(content);
    }

    // 讯飞对话历史展现
    @PostMapping("/getChatList")
    public ResponseEntity getChatList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int model = AiModelEnum.XUNFEI.getValue();
        int type = AiTypeEnum.CHAT.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model,type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if(list == null)  {
            // 缓存不在
            // 从数据库中查询
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("type", type);
            queryWrapper.eq("model", model);
            queryWrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(queryWrapper);
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        }else {
            return ResponseEntity.succ(list);
        }
    }

    /**
     * 讯飞绘图功能
     */
    @Idempotent
    @PostMapping("/draw")
    public ResponseEntity draw(String question) throws Exception {
        if (!StringUtils.hasLength(question)) {
            return ResponseEntity.fail("问题不能为空");
        }
        // 执行分布式锁
        Long uid = SecurityUtil.getCurrentUser().getUid();
        String lockKey = AppVariable.getModelLockKey(uid,
                AiModelEnum.XUNFEI.getValue(),
                AiTypeEnum.DRAW.getValue());
        String result = ""; // 大模型返回的结构
        String content = "";
        // base64 -> minio
        String imgUrl = "";
        boolean isSave = false; // 数据添加状态
        // 获取分布式锁实例
        RLock rLock = redissonClient.getLock(lockKey);
        try {
            boolean isLock = rLock.tryLock(30, TimeUnit.SECONDS);
            if (!isLock) {
                // 获取分布式锁失败
                return ResponseEntity.fail("请勿频繁请求，请稍后再试");
            }
            String url = getAuthUrl(hostUrl, drawApiKey, drawApiSecret);
            String json = "{\n" +
                    "  \"header\": {\n" +
                    "    \"app_id\": \"" + appId + "\"\n" +
                    "    },\n" +
                    "  \"parameter\": {\n" +
                    "    \"chat\": {\n" +
                    "      \"domain\": \"general\",\n" +
                    "      \"width\": 512,\n" +
                    "      \"height\": 512\n" +
                    "      }\n" +
                    "    },\n" +
                    "  \"payload\": {\n" +
                    "    \"message\": {\n" +
                    "      \"text\": [\n" +
                    "        {\n" +
                    "          \"role\": \"user\",\n" +
                    "          \"content\": \"" + question + "\"\n" +
                    "        }\n" +
                    "      ]\n" +
                    "    }\n" +
                    "  }\n" +
                    "}";
            result = HttpRequest.post(url)
                    .body(json)
                    .execute()
                    .body();
            HashMap<String, Object> resultMap = objectMapper.readValue(result, HashMap.class);
            LinkedHashMap<String, Object> payload = (LinkedHashMap<String, Object>) resultMap.get("payload");
            LinkedHashMap<String, Object> choices = (LinkedHashMap<String, Object>) payload.get("choices");
            ArrayList<LinkedHashMap<String, Object>> text = (ArrayList<LinkedHashMap<String, Object>>) choices.get("text");
            LinkedHashMap<String, Object> contentMap = text.get(0);
            content = contentMap.get("content").toString();
            // 这里自动释放资源
            try (ByteArrayInputStream inputStream = new
                    ByteArrayInputStream(Base64.getDecoder().decode(content))) {
                String imgName = "xf-draw-" + UUID.randomUUID().toString()
                        .replace("-", "");
                imgUrl = minioUtil.upload(imgName, inputStream, "image/png");
            }

            Answer answer = new Answer();
            answer.setTitle(question);
            answer.setContent(imgUrl);
            answer.setModel(AiModelEnum.XUNFEI.getValue());
            answer.setType(AiTypeEnum.DRAW.getValue());
            answer.setUid(uid);
            isSave = answerService.save(answer);
        } catch (Exception e) {
        } finally {
            rLock.unlock();
        }
        if(!isSave) {
            return ResponseEntity.fail("数据保存失败，请重试");
        }
        return ResponseEntity.succ(imgUrl);
    }

    /**
     * 讯飞大模型 URL 签名方法
     */
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // date="Thu, 12 Oct 2023 03:05:28 GMT";
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" + "date: " + date + "\n" + "POST " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();
        return httpUrl.toString();
    }

    // 讯飞绘图历史展现
    @PostMapping("/getDrawList")
    public ResponseEntity getDrawList() {
        Long uid = SecurityUtil.getCurrentUser().getUid();
        int type = AiTypeEnum.DRAW.getValue();
        int model = AiModelEnum.XUNFEI.getValue();
        String cacheKey = AppVariable.getListCacheKey(uid, model, type);
        Object list = redisTemplate.opsForValue().get(cacheKey);
        if (list == null) {
            QueryWrapper<Answer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            queryWrapper.eq("type", type);
            queryWrapper.eq("model", model);
            queryWrapper.orderByDesc("aid");
            List<Answer> dataList = answerService.list(queryWrapper);
            redisTemplate.opsForValue().set(cacheKey, dataList, 1, TimeUnit.DAYS);
            return ResponseEntity.succ(dataList);
        } else {
            return ResponseEntity.succ(list);
        }
    }
}
